/**
 * @Description friendFarm-view
 * @author lizhilin
 * @update 2016-08-18
 */
define(function(require, exports, modules) {
	'use strict';

	require('css!assets/css/style.css');

	var template = require('text!./tpl.friendFarm.html'),
		util = require('util');
	var View = Backbone.View.extend({
		el : '#page',
		events : {
			'click em.back': function () {
				Backbone.history.navigate('farm',{trigger:true});
			},
			'click em.refresh': function () {
				this.render();
			},
			//弹窗显示临时控制
			'click .chicken-page>.notice em': function () {
				this.show_shade('notice');
				var userStr = util.getCookie('user');
				var user = $.parseJSON(userStr);
				jsonpGet(
						util.server+'/getNoticeList',
						{
							userId: user.userId,
							token: user.token
						},
						'getNoticeList',
						$.proxy(function (res) {
							if(res.code == 1){
								$('section.shade .notice ul').empty();
								$.each(res.data, function (index, ele) {
									$('section.shade .notice ul').append(
									'<li>'+
										'<div class="top">'+
											'<div class="name">'+ele.noticeTitle+'</div>' +
											'<time>'+formatDate(new Date(ele.createTime),5)+'</time>'+
										'</div>'+
										'<p>'+ele.noticeContent+'</p>'+
									'</li>'
									);
								});
								$('section.shade .notice ul li').eq(1).addClass('cur');
							}else {
								commonAlert_oneBtn('请求失败');
							}
						},this)
					)
			},
			'click section.shade .cleanCheck button': function (e) {
				this.hide_shade();
			},
			//弹窗元素临时控制
			'click i.close': function () {
				this.hide_shade();
			},
			'click section.shade .notice li': function (e) {
				var _this = $(e.currentTarget);
				_this.siblings().removeClass('cur');
				if(_this.hasClass('cur')){
					_this.children('p').slideToggle(200);
				}else{
					_this.children('p').slideDown(200).end().siblings().children('p').slideUp(200);
					_this.addClass('cur');
				}
			}
		},
		initialize : function() {
			var userStr = util.getCookie('user');
			var user = $.parseJSON(userStr);
			if(!user){
				Backbone.history.navigate('loading',{trigger:true});
				return;
			}
			if(user.userStatus == 3){
				Backbone.history.navigate('home',{trigger:true});
				return;
			}
			this.template = _.template(template);
			this.render();
		},
		render : function() {
			this.$el.html(this.template());
			//this.setting();
			this.loadData();
		},
		loadData:function(){
			var friendId = util.getQueryString('friendId');
			if(friendId){
				this.friendId = friendId;
				var userStr = util.getCookie('user');
				var user = $.parseJSON(userStr);
				this.user = user;
				var _this = this;
				jsonpGet(util.NDNserver+'/enterFriendFarm',{userId: user.userId,token: user.token,friendId: friendId},'enterFriendFarm',$.proxy(function(json){
					if(json.code == '1'){
						var data = json.data;
						console.log(data);
						_this.farmData = data;
						_this.setData(data);
					}
				},this),
				$.proxy(function(){
					_this.setting();
				},this));
			}
		},
		setData:function(data){
			var _this = this;
			if(data){
				$('.userBox .name').text(data.loginName ? data.loginName : ' ');
				$('.userBox .myheadImg').css({'background-image': data.userPic && data.userPic.length>0 ? "url('"+data.userPic+"')" : "url('assets/images/home/portrait/portrait-man.png')"});
				//鸡蛋与鸡显示处理
				var totalEgg = data.totalEgg ? data.totalEgg : 0;
				var totalChicken = data.totalChicken ? data.totalChicken : 0
				if($(window).width()<375){
					$('.userBox .clm').addClass('round');
					if(totalEgg>9999){
						totalEgg = parseFloat(totalEgg/10000).toFixed(1)+'万';
					}else if(totalEgg>99999){
						totalEgg = parseFloat(totalEgg/10000).toFixed(0)+'万';
					}else if(totalEgg > 999){
						totalEgg = parseFloat(totalEgg).toFixed(0);
					}else{
						totalEgg = parseFloat(totalEgg).toFixed(1);
					}
					if(totalChicken>9999){
						totalChicken = parseFloat(totalChicken/10000).toFixed(1)+'万';
					}else if(totalChicken>99999){
						totalChicken = parseFloat(totalChicken/10000).toFixed(0)+'万';
					}else if(totalChicken>999){
						totalChicken = parseFloat(totalChicken).toFixed(0);
					}else{
						totalChicken = parseFloat(totalChicken).toFixed(1);
					}
				}else{
					totalEgg = parseFloat(totalEgg).toFixed(1);
					totalChicken = parseFloat(totalChicken).toFixed(1);
				}
				document.querySelector('.userBox .clm-l').innerText = totalEgg;
				document.querySelector('.userBox .clm-r').innerText = totalChicken;
				//公告设置
				$('.notice p span').text(data.notice ? data.notice.noticeTitle : '');
				//养鸡地设置
				var add_chicken = function (index,num) {
					for(var i= 0; i < num; i++){
						_this.addChicken(index);
					}
				}
				for(var i = 0; i < data.landList.length; i++){
					//地块信息
					var land = data.landList[i];
					var currLand = $('.fieldBox ul.field li:eq('+(1*land.code - 1)+')');
					currLand.data('chicksNum',land.chicksNum);
					currLand.data('maxNum',land.maxNum);
					currLand.data('minNum',land.minNum);
					currLand.data('eggsIncome',land.eggsIncome);//今日产蛋
					currLand.data('totalIncome',land.totalIncome);//历史产蛋
					currLand.data('id',land.id);//地块id
					//加载小鸡
					var chicksNum = land.chicksNum, maxNum = land.maxNum;
					if(chicksNum <= maxNum/4){
						add_chicken(1*land.code - 1,1);
					}else if(maxNum/4 < chicksNum && chicksNum <= maxNum/4*2 ){
						add_chicken(1*land.code - 1,2);
					}else if(maxNum/4*2 < chicksNum && chicksNum <= maxNum/4*3){
						add_chicken(1*land.code - 1,3);
					}else if(maxNum/4*3 < chicksNum && chicksNum <= maxNum){
						add_chicken(1*land.code - 1,4);
					}
					//围栏设置
					if(data.fence){
						$('.fieldBox li:eq('+(1*land.code - 1)+')').addClass('lv'+ data.fence.fenceLevel ? data.fence.fenceLevel : 1);
					}
				}
				//狗设置
				if(data.dog){
					$('.dog').show();
					$('.dog img').attr('src','assets/images/farm/dog/0'+(data.dog.dogLevel ? data.dog.dogLevel : '1')+'.gif')
				}
				//打扫设置
				if(data.isCleanFriend && data.isCleanFriend == '1'){
					$('.desktop button.clean').removeClass('cur');
				}else{
					$('.desktop button.clean').addClass('cur');
				}
				
				this.setting();
			}
		},
		setting:function(){
			//page
			var V_this = this;
			var section = document.querySelector('.userBox section');
			var $_field = $('ul.field li');
			function setSection (){
				section.style.lineHeight = $(section).height()+'px';
				$_field.height($_field.width() *217/230);
				var userAgent = navigator.userAgent.toLowerCase();
				var mobile = userAgent.match(/(iphone|ipod|android|ios|ipad)/i);
				var isPC = !mobile;
				if(isPC){
					$('.fieldBox .middleware').css({'overflow': 'hidden'});
					$('.desktop').width($('#page').width()).css({'margin': 'auto','left': 'initial'});
					$('.floor-bg').width($('#page').width());
					$('section.shade').width($('#page').width()).css({'margin': 'auto','left': 'initial'});
					$('.dog').css({'left': 'initial'});
				}
			};
			document.querySelector('.bg').onload = function () { setSection ();}
			window.onresize = function () { setSection ();}
			$(document).ready(function(){ setSection ();})

			!function dog(){
				var eX,eY;
				var dogX,dogY;
				var touchInnerX,touchInnerY;
				var dog = document.querySelector('.dog');
				var dogWidth = dog.offsetWidth;
				var dogHeight= dog.offsetHeight;
				var dogMaxX,dogMinY=document.querySelector('.vine').offsetHeight,dogMaxY=document.querySelector('.desktop').offsetTop-dogHeight;
				dog.style.top = dogMaxY+'px';

				dog.addEventListener('touchstart',touch, false);
				dog.addEventListener('touchmove',touch, false);
				dog.addEventListener('touchend',touch, false);

				function touch (event){
					var event = event || window.event;

					switch(event.type){
						case "touchstart":
							event.preventDefault();
							eX = event.touches[0].clientX;
							eY = event.touches[0].clientY;
							dogX = dog.offsetLeft;
							dogY = dog.offsetTop;
							touchInnerX = eX-dogX;
							touchInnerY = eY-dogY;
							dogMaxX = $('body').width()-(dogWidth)
							break;
						case "touchend":
							event.preventDefault();
							//event.changedTouches[0].clientX;event.changedTouches[0].clientY;
							if(dog.offsetLeft < ($('body').width()-dogWidth)/2){
								$(dog).animate({'left':0},300);
							}else{
								$(dog).animate({'left':dogMaxX},300);
							}
							break;
						case "touchmove":
							event.preventDefault();
							dogX = event.touches[0].clientX - touchInnerX;
							dogY = event.touches[0].clientY - touchInnerY;

							if(dogX>dogMaxX){
								dog.style.left = dogMaxX+'px';
							}else if(dogX<0){
								dog.style.left = 0;
							}else {
								dog.style.left = dogX+'px';
							}

							if(dogY<dogMinY){
								dog.style.top = dogMinY+'px';
							}else if(dogY>dogMaxY){
								dog.style.top = dogMaxY+'px';
							}else{
								dog.style.top = dogY+'px';
							}

							break;
					}
				}
			}();

			//点击地块
			$('ul.field li').click(function () {
				var _this = $(this);
				_this.addClass('clicked');
				//有鸡地块 动态添加详情
				if(_this.find('.chicken-box').length != 0 && !_this.hasClass('canUp')){
					_this.find('.Bubble').append(
						'<div class="clickShowBox show">'+
						'<p><b>小鸡总数:</b><em>'+_this.data('chicksNum')+'</em></p>'+
						'<p><b>本日产蛋:</b><em>'+_this.data('eggsIncome')+'</em></p>'+
						'<p><b>历史产蛋:</b><em>'+_this.data('totalIncome')+'</em></p>'+
						'<i></i>'+
						'</div>'
					);
					$('body').append(
						'<section class="clickShowBox-shade"></section>'
					);
					$('.clickShowBox-shade').click(function () {
						$(this).remove();
						_this.find('.clickShowBox').remove();
					});
					if(_this.index() < 4)$('.Bubble .clickShowBox').css({'top': '0'});
				}
			});

			//button打扫
			$('.desktop button').click(function () {
				if(! $(this).hasClass('cur')){
					$(this).addClass('cur');
					$('section.shade').addClass('showClean');
					setTimeout(function () {
						$('section.shade').removeClass('showClean');
						if(V_this.farmData){
							jsonpGet(util.NDNserver+'/cleanFriendFarm',{userId: V_this.user.userId,token: V_this.user.token,friendId: V_this.friendId},'cleanFriendFarm',$.proxy(function(json){
								if(json.code == '1'){
									V_this.show_shade('cleanCheck');
									$('section.shade .cleanCheck p em').text(json.data.toFixed(2) + '只');
								}else{
									commonAlert_oneBtn('打扫失败');
								}
							},this));
						}
					},4000);
				}
			});
		},
		hide_shade: function () {
			$('section.shade').hide(0);
			$('section.shade >div').hide(0);
		},
		show_shade: function (ele) {
			$('section.shade').show(0);
			$('section.shade > .'+ele).show(0);
		},
		addChicken: function (index) {
			var addChicken = {
				init: function (index) {
					if(parseInt(Math.random()*2)){
						$('ul.field li').eq(index).append(
							'<div class="chicken-box"><i class="chicken-run"></i></div>');
						this.move(index);
					}else {
						$('ul.field li').eq(index).append(
							'<div class="chicken-box"><i class="chicken-walk"></i></div>');
						this.move(index);
					}
				},
				move: function (i) {
					if($('ul.field li').eq(i).find('i').eq(-1).hasClass('chicken-run')){
						$('ul.field li').eq(i).find('.chicken-box').eq(-1).addClass('run-move');
					}else{
						$('ul.field li').eq(i).find('.chicken-box').eq(-1).addClass('walk-move')
							.css({
								'left':Math.random()*4.6+'rem'
							})
					}
					var n = parseInt(Math.random()*6);
					$('ul.field li').eq(i).find('.chicken-box').eq(-1).css({
						'animation-delay': -n+'s',
						'top': Math.random()*2.2-1+'rem'
					})
					$('ul.field li').eq(i).find('i').eq(-1).css({
						'animation-delay': -n+'s'
					})

					this.lay(i);
				},
				lay: function (i) {
					var tops = [];
					//var maxIndex = tops.indexOf(Math.max.apply(Math, tops));
					$('ul.field li').eq(i).find('.chicken-box').each(function (index, ele) {
						tops[index] = ele.style.top.replace('rem','')*100;//100扩大精度
					});

					var Max, Min;
					var Max_index, Min_index;
					function MaxAndMin(arr){
						Max = arr[0];
						Min = Max;
						for(var i in arr){
							if(arr[i]>Max){
								Max = arr[i];
								Max_index = i;
							}
						}
						for(var p in arr){
							if(arr[p]<Min){
								Min = arr[p];
								Min_index = p;
							}
						}
					};

					MaxAndMin(tops);

					if(tops.length != 1){
						$('ul.field li').eq(i).find('.chicken-box').css({'z-index':'2'});
						$('ul.field li').eq(i).find('.chicken-box').eq(Min_index).css({'z-index':'1'});
						$('ul.field li').eq(i).find('.chicken-box').eq(Max_index).css({'z-index':'3'});
					}
				}
			}
			addChicken.init(index);
		}
	});
	return View;
});